package com.wondersgroup.controller;

import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.wondersgroup.aop.Submit;
import com.wondersgroup.entity.Company;
import com.wondersgroup.entity.CompanyVo;
import com.wondersgroup.entity.Record;
import com.wondersgroup.entity.RecordVo;
import com.wondersgroup.service.CompanyService;
import com.wondersgroup.service.RecordService;
import com.wondersgroup.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/company")
public class CompanyController {


  @Autowired
  private CompanyService companyService;

  @Autowired
  private RecordService recordService;

  private static SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd HH:mm:ss");

  /**
   * 单位注册
   */
  @Submit
  @RequestMapping("/register")
  @ResponseBody
  public Map<String, Object> register(@RequestBody Company company) {
    Map<String, Object> map = new HashMap<>();
    if (company.getId() == null || company.getId().equals("") ||
      company.getDwmc() == null || company.getDwmc().equals("") ||
      company.getDwdz() == null || company.getDwdz().equals("") ||
      company.getSqrxm() == null || company.getSqrxm().equals("") ||
      company.getSqrzjlx() == null || company.getSqrzjlx().equals("") ||
      company.getSqrzjhm() == null || company.getSqrzjhm().equals("") ||
      company.getSqrsjh() == null || company.getSqrsjh().equals("")) {
      map.put("code", 500);
      map.put("msg", "参数不能为空！");
      return map;
    }
    Company cc = companyService.getCompanyById(company.getId());
    if (cc != null) {
      map.put("code", "501");
      map.put("msg", "重复注册！");
      return map;
    }
    //解密
    String sqrxm = null;
    String sqrsjh = null;
    String sqrzjhm = null;
    try {
      sqrxm = RsaUtil.getDecData(company.getSqrxm());
      System.out.println("转码前---" + sqrxm);
      sqrxm = URLDecoder.decode(sqrxm, "UTF-8");
      System.out.println("转码后---" + sqrxm);
      sqrsjh = RsaUtil.getDecData(company.getSqrsjh());
      sqrzjhm = RsaUtil.getDecData(company.getSqrzjhm());
    } catch (Exception e) {
      e.printStackTrace();
      map.put("code", 500);
      map.put("msg", "解密异常！");
      return map;
    }
    // 校验手机
    Boolean b = RegUtil.isMobile(sqrsjh);
    if (b == false) {
      map.put("code", 500);
      map.put("msg", "请输入正确的手机号！");
      return map;
    }
    Boolean bb = RegUtil.isIDNumber(sqrzjhm);
    if (bb == false) {
      map.put("code", 500);
      map.put("msg", "请输入正确的证件号码！");
      return map;
    }
    company.setSqrxm(sqrxm);
    company.setSqrsjh(sqrsjh);
    company.setSqrzjhm(sqrzjhm);
    company.setSqsj(new Date());
    company.setXgsj(new Date());
    company.setYxbz("1");//默认为有效
    try {
      CompanyVo vo = companyService.register(company);
      map.put("code", 200);
      map.put("company", vo);
    } catch (Exception e) {
      e.printStackTrace();
      map.put("code", 500);
      map.put("msg", "注册异常！");
      return map;
    }
    return map;
  }


  /**
   * 是否注册
   */
  @RequestMapping("/isRegister")
  @ResponseBody
  public Map<String, Object> isRegister(@RequestBody Map<String, Object> param) {
    Map<String, Object> map = new HashMap<>();
    String openId = param.get("openId") != null ? param.get("openId").toString() : null;
    if (openId == null || openId.equals("")) {
      map.put("code", 500);
      map.put("msg", "参数不能为空！");
      return map;
    }
    Company company = companyService.getCompanyById(openId);
    if (company == null) {
      map.put("code", 200);
      map.put("msg", "未注册！");
    } else {
      map.put("code", 500);
      map.put("msg", "已注册！");
    }
    return map;
  }


  /**
   * 登录
   */
  @Submit
  @RequestMapping("/login")
  @ResponseBody
  public Map<String, Object> login(@RequestBody Map<String, Object> param) {
    Map<String, Object> map = new HashMap<>();
    String sqrsjh = param.get("sqrsjh") != null ? param.get("sqrsjh").toString() : null;
    String sqrzjhm = param.get("sqrzjhm") != null ? param.get("sqrzjhm").toString() : null;
    String yzm = param.get("yzm") != null ? param.get("yzm").toString() : null;
    String openId = param.get("openId") != null ? param.get("openId").toString() : null;
    String sqrzjlx = param.get("sqrzjlx") != null ? param.get("sqrzjlx").toString() : null;
    if (sqrsjh == null || sqrsjh.equals("") ||
      sqrzjhm == null || sqrzjhm.equals("") ||
      sqrzjlx == null || sqrzjlx.equals("") ||
      yzm == null || yzm.equals("") ||
      openId == null || openId.equals("")) {
      map.put("code", 500);
      map.put("msg", "参数不能为空!");
      return map;
    }
    //解密
    try {
      sqrsjh = RsaUtil.getDecData(sqrsjh);
      sqrzjhm = RsaUtil.getDecData(sqrzjhm);
      Boolean b = RegUtil.isMobile(sqrsjh);
      if (b == false) {
        map.put("code", 500);
        map.put("msg", "请输入正确的手机号！");
        return map;
      }
      Boolean b1 = RegUtil.isIDNumber(sqrzjhm);
    } catch (Exception e) {
      e.printStackTrace();
      map.put("code", 500);
      map.put("msg", "解密异常！");
      return map;
    }
    try {
      map = companyService.login(sqrsjh, sqrzjhm, yzm, openId);
    } catch (Exception e) {
      e.printStackTrace();
      map.put("code", 500);
      map.put("msg", "加密异常");
      return map;
    }
    return map;
  }


  /**
   * 传入参数：
   * 必填：
   * dwid  单位ID
   * xm    姓名
   * ksrq  开始日期
   * jsrq  结束日期
   * pageSize 每页大小
   * pageIndex 第几页
   * <p>
   * 不填时间 默认 最近一天有记录的日期
   */
  @RequestMapping("/companyRecord")
  @ResponseBody
  public Map<String, Object> companyRecord(@RequestBody Map<String, Object> param) {
    Map<String, Object> map = new HashMap<>();
    String dwid = param.get("dwid").toString();
    String djsj_start = param.get("djsj_start").toString();
    String djsj_end = param.get("djsj_end").toString();
    String xm = param.get("xm").toString();
    int pageIndex = param.get("pageIndex") != null ? Integer.parseInt(param.get("pageIndex").toString()) : 1;
    int pageSize = param.get("pageSize") != null ? Integer.parseInt(param.get("pageSize").toString()) : 10;
    int rowIndex = PageCalculaterUtil.getRowIndex(pageIndex, pageSize);
    if (dwid.equals("")) {
      map.put("code", 500);
      map.put("msg", "参数不能为空!");
      return map;
    }
    //页码 与 每页数据数 校验
    if (pageIndex < 1 || pageSize < 1) {
      map.put("code", 500);
      map.put("msg", "请输入正确的参数!");
      return map;
    }
    if (!xm.equals("")) {
      try {
        xm = RsaUtil.getDecData(xm);
      } catch (Exception e) {
        e.printStackTrace();
        map.put("code", 500);
        map.put("msg", "解密异常！");
        return map;
      }
    }
    //校验开始时间与结束时间 大小比较
    if (!djsj_start.equals("") && !djsj_end.equals(""))  {
      Date start = null;
      Date end = null;
      try {
         start = sdf.parse(djsj_start);
         end = sdf.parse(djsj_end);
        int b = start.compareTo(end);
        if (b > 0) {
          map.put("code", 500);
          map.put("msg", "结束日期不能小于开始日期！");
          return map;
        }
      } catch (ParseException e) {
        map.put("code", 500);
        map.put("msg", "日期转换异常！");
        return map;
      }

    }
    try {
      //  根据单位id 开始时间 结束时间 获取 访客记录
      List<RecordVo> recordList = new ArrayList<>();
      //先根据 dwid查询该机构是否有访问记录 如果没有  直接返回 空集合
      List<Record> result = recordService.getCompanyRecords(dwid);
      if (result.size() < 1) {
        map.put("code", 200);
        map.put("recordList", recordList);
        return map;
      }
      // 前台是否是默认 条件
      if (djsj_start.equals("") && djsj_end.equals("") && xm.equals("")) {
        Date kssj = null;
        Date jssj = null;
        int i = 0;
        while (recordList.size() < 1) {
          Date currDate = TimeUtil.getSomeDay(new Date(), i);
          kssj = TimeUtil.getStartTime(currDate);
          jssj = TimeUtil.getEndTime(currDate);
          recordList = recordService.getRecordsByDate(dwid, kssj, jssj, rowIndex, pageSize, xm);
          i--;
        }
      } else {
        Date kssj = null;
        Date jssj = null;
        //开始时间
        if (!djsj_start.equals("")) {
          Date date = sdf.parse(djsj_start);
          kssj = TimeUtil.getStartTime(date);
        }
        //结束时间
        if (!djsj_end.equals("")) {
          Date date = sdf.parse(djsj_end);
          jssj = TimeUtil.getEndTime(date);
        }
        recordList = recordService.getRecordsByDate(dwid, kssj, jssj, rowIndex, pageSize, xm);
      }
      map.put("code", 200);
      map.put("recordList", recordList);
      return map;
    } catch (Exception e) {
      e.printStackTrace();
      map.put("code", 500);
      map.put("msg", "操作异常");
      return map;
    }
  }

  /**
   * 生成验证码图片 经base64转码
   *
   * @param request
   * @return
   */
  @RequestMapping("/getPictureCode")
  @ResponseBody
  public Map<String, Object> getPictureCode(HttpServletRequest request) {
    Map<String, Object> map = new HashMap<>();
    String param = "ImgVerificationCodeMark";
    String base64ImgStr = companyService.createPicVerificationCode(param, request);
    if (base64ImgStr == null) {
      map.put("code", 500);
      map.put("msg", "生成验证码失败,请重试！");
    } else {
      map.put("code", 200);
      map.put("data", base64ImgStr);
    }
    return map;
  }


  /**
   * 获取 签到明细
   *
   * @param param
   * @return
   */
  @RequestMapping("/getDetail")
  @ResponseBody
  public Map<String, Object> getDetail(@RequestBody Map<String, Object> param) {
    Map<String, Object> map = new HashMap<>();
    String dwid = param.get("dwid") != null ? param.get("dwid").toString() : null;
    String djsj = param.get("djsj") != null ? param.get("djsj").toString() : null;
    String sjh = param.get("sjh") != null ? param.get("sjh").toString() : null;
    String type = param.get("type") != null ? param.get("type").toString() : null;
    if (djsj == null || djsj.equals("") || sjh == null || sjh.equals("") || type == null || type.equals("")) {
      map.put("code", 500);
      map.put("msg", "参数不能为空！");
      return map;
    }
    //解密
    try {
      sjh = RsaUtil.getDecData(sjh);
      Boolean b = RegUtil.isMobile(sjh);
      if (b == false) {
        map.put("code", 500);
        map.put("msg", "请输入正确的手机号！");
        return map;
      }
      Date date_djsj = sdf.parse(djsj);
      //根据  登记时间 手机号 获取记录
      Record record = recordService.getDetail(dwid, sjh, date_djsj, type);
      map.put("code", 200);
      map.put("record", record);
    } catch (Exception e) {
      e.printStackTrace();
      map.put("code", 500);
      map.put("msg", "获取异常！");
      return map;
    }
    return map;
  }


  /**
   * 二维码 查看
   *
   * @param request
   * @param response
   * @throws IOException
   */
  @RequestMapping("/qrdView")
  public void getCode(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String, Object> param) {
    String dwid = param.get("dwid") != null ? param.get("dwid").toString() : null;
    String content = getLocalUrl(request, dwid);
    BitMatrix bitMatrix = null;
    OutputStream out = null;
    try {
      //获取一个二维码图片
      System.out.println("content..." + content);
      bitMatrix = QRCodeUtils.createCode(content);
      // 设置响应流信息
      response.setContentType("image/jpg");
      response.setHeader("Pragma", "no-cache");
      response.setHeader("Cache-Control", "no-cache");
      response.setDateHeader("Expires", 0);
      out = response.getOutputStream();
      //以流的形式输出到前端
      MatrixToImageWriter.writeToStream(bitMatrix, "jpg", out);
    } catch (IOException e) {
      e.printStackTrace();
      try {
        if (out != null) {
          out.close();
        }
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }

  /**
   * 二维码下载
   *
   * @param request
   * @param response
   * @throws Exception
   */
  @RequestMapping("/qrdDownload")
  public void qrdDownload(HttpServletRequest request, HttpServletResponse response, @RequestBody Map<String, Object> param) {
    String dwid = param.get("dwid") != null ? param.get("dwid").toString() : null;
    String content = getLocalUrl(request, dwid);
    //获取一个二维码图片
    BitMatrix bitMatrix = null;
    OutputStream out = null;
    try {
      bitMatrix = QRCodeUtils.createCode(content);
      response.setHeader("Content-Type", "application/octet-stream");
      response.setHeader("Content-Disposition",
        "attchement;filename=" + new String("二维码.jpg".getBytes("gb2312"), "ISO8859-1"));
      out = response.getOutputStream();
      MatrixToImageWriter.writeToStream(bitMatrix, "jpg", out);
      out.flush();
      out.close();
    } catch (IOException e) {
      e.printStackTrace();
      try {
        if (out != null) {
          out.close();
        }
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }

  /**
   * 获取完整的url
   *
   * @param request
   * @return
   */
  private String getLocalUrl(HttpServletRequest request, String dwid) {
    String local_url = "http://localhost:8080/wx/login/" + dwid;
    String urls = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx520c15f417810387&redirect_uri=https%3A%2F%2Fchong.qq.com%2Fphp%2Findex.php%3Fd%3D%26c%3DwxAdapter%26m%3DmobileDeal%26showwxpaytitle%3D1%26vb2ctag%3D4_2030_5_1194_60&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
    try {
      System.out.println("转码前:" + local_url);
      String redirect_uri = URLEncoder.encode(local_url, "UTF-8");
      System.out.println("转码后:" + redirect_uri);
      String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
        "appid=wx24c55f38b535cd96" +
        "&redirect_uri=REDIRECT_URI" +
        "&response_type=code" +
        "&scope=snsapi_base" +
        "&state=123#wechat_redirect";
      url = url.replace("REDIRECT_URI", redirect_uri);
      return url;
    } catch (Exception e) {
      e.printStackTrace();
      return "";
    }
  }


}
